//
//  FSWebViewController.m
//  FSiOSClient
//
//  Created by purlible on 2024/10/8.
//

#import "FSWebViewController.h"
#import <WebKit/WKWebView.h>
#import <WebKit/WebKit.h>
#import <dsBridge/dsbridge.h>

@interface FSWebViewController ()<WKNavigationDelegate>

@property(nonatomic, strong) UIProgressView *progressView;
@property(nonatomic, strong) FSWebModel *webModel;

@end

@implementation FSWebViewController

- (instancetype)initWithModel:(FSWebModel *)webModel
{
    self = [super init];
    if (self)
    {
        self.webModel = webModel;
        self.modalPresentationStyle = UIModalPresentationOverFullScreen;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    self.title = isNull(self.webModel.autoTitle) ?  self.webView.title : self.webModel.autoTitle;
        
    _webView = [[DWKWebView alloc] init];
    _webView.backgroundColor = UIColor.whiteColor;
    [_webView setAllowsBackForwardNavigationGestures:YES];
    _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  
    [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    [_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    [_webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:NULL];
    [self.view addSubview:_webView];
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(APPLICATION_TOP_BAR_HEIGHT);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    UIImage* barImage = [[UIImage imageNamed:@"web_icon_close"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem* backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:barImage style:UIBarButtonItemStylePlain target:self action:@selector(leftArrowAct)];
    [self.navigationItem setRightBarButtonItems:@[backBarButtonItem] animated:YES];
    
    if(!isNull(self.webModel.url))
    {
        [self loadWebViewUrl:self.webModel.url];
    }
    else if(!isNull(self.webModel.content))
    {
        [_webView loadHTMLString:self.webModel.content baseURL:nil];
    }
    else if (!isNull(self.webModel.localUrlName))
    {
        NSString *htmlFile = [[NSBundle mainBundle] pathForResource:self.webModel.localUrlName ofType:@"html"];
        NSError *error = nil;
        
        NSString *htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:&error];
        
        if (error) {
            NSLog(@"读取 HTML 文件失败: %@", error.localizedDescription);
            return;
        }
        
        if (![[NSFileManager defaultManager] fileExistsAtPath:htmlFile]) {
            NSLog(@"文件不存在: %@", htmlFile);
        }
        
        // 加载 HTML 内容
        NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
        [self.webView loadHTMLString:htmlString baseURL:baseURL];
    }
    
    _progressView  = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    _progressView.trackTintColor = [UIColor clearColor];
    _progressView.progressTintColor = UIColorHex(#56A890);
    [self.view addSubview:_progressView];
    [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(APPLICATION_TOP_BAR_HEIGHT);
        make.left.right.equalTo(self.view);
        make.height.scale_equalTo(3);
    }];
    
    WKUserScript *script = [[WKUserScript alloc] initWithSource:@"chatrbot = {};"
                                                  injectionTime:WKUserScriptInjectionTimeAtDocumentStart
                                               forMainFrameOnly:YES];
    [_webView.configuration.userContentController addUserScript:script];
}


- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)loadWebViewUrl:(NSString *)urlStr
{
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}


- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    if( !isNull(_progressView) )
    {
        self.progressView.hidden = NO;
    }
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
{
    [self showError:@"加载失败!"];
    
    if( !isNull(_progressView) )
    {
        self.progressView.hidden = YES;
    }
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if(object == _webView)
    {
        if ([keyPath isEqualToString:@"estimatedProgress"] && !isNull(_progressView) )
        {
            [_progressView setAlpha:1.0f];
            BOOL animated = _webView.estimatedProgress > _progressView.progress;
            [_progressView setProgress:_webView.estimatedProgress animated:animated];
            
            if (_webView.estimatedProgress >= 1.0f) {
                FSWeakSelf
                [UIView animateWithDuration: 0.1f
                                      delay: 0.5f
                                    options: UIViewAnimationOptionCurveEaseOut
                                 animations: ^{
                                     [weakSelf.progressView setAlpha:0.0f];
                                 }
                                 completion:^(BOOL finished) {
                                     [weakSelf.progressView setProgress:0.0f animated:NO];
                                 }];
            }
        }
        else if ([keyPath isEqualToString:@"title"])
        {
            self.title = isNull(self.webModel.autoTitle) ?  self.webView.title : self.webModel.autoTitle;
        }
    }
}


//-(void) refershBackBtn
//{
//    UIImage* barImage = [[UIImage imageNamed:@"web_icon_close"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    UIBarButtonItem* backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:barImage style:UIBarButtonItemStylePlain target:self action:@selector(leftArrowAct)];
//    
//    if(!self.webView.canGoBack)
//    {
//        [self.navigationItem setLeftBarButtonItems:@[backBarButtonItem] animated:YES];
//    }
//    else
//    {
//        UIImage* closeIcon = [[UIImage imageNamed:@"web_icon_close"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//        UIBarButtonItem *webBackBtn = [[UIBarButtonItem alloc] initWithImage:closeIcon style:UIBarButtonItemStylePlain target:self action:@selector(_back)];
//        
//        [self.navigationItem setLeftBarButtonItems:@[ backBarButtonItem, webBackBtn ]  animated:YES];
//    }
//}

- (void)leftArrowAct
{
    if(_webView.canGoBack)
    {
        [_webView goBack];
    }
    else
    {
        [self back];
    }
}

-(void) dealloc
{
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [_webView removeObserver:self forKeyPath:@"title"];
    [_webView removeObserver:self forKeyPath:@"canGoBack"];
}

@end
